package com.ams.thread.lesson1;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author： 乐哥聊编程(全平台同号)
 */
@Slf4j
public class Example2 {
    private static volatile boolean start = false;
    private static volatile boolean end = false;


    public static void main(String[] args) {
        List<Job> jobs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Job job = new Job(i % 2 == 0 ? 1 : 10);
            jobs.add(job);
            Thread thread = new Thread(job);
            thread.setName("线程："+i);
            thread.setPriority(job.priority);
            thread.start();
        }
        start = true;
        ThreadUtil.sleep(1000);
        end = true;
        List<Job> sortJob = jobs.stream().sorted(new Comparator<Job>() {
            @Override
            public int compare(Job o1, Job o2) {
                return o1.count - o2.count;
            }
        }).collect(Collectors.toList());
        for (Job job : sortJob) {
            log.info("线程：{} 优先级 {} 计数: {}", job.name, job.priority,job.count);
        }

    }

    static class Job implements Runnable {
        private int priority;
        private int count;
        private String name;

        public Job(int property) {
            this.priority = property;
        }

        @Override
        public void run() {
            this.name = Thread.currentThread().getName();
            while (!start) {
                Thread.yield();
            }
            while (!end) {
                Thread.yield();
                count++;
            }
        }
    }
}
